package com.lening.communitylog.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lening.common.base.BaseServiceImpl;
import com.lening.communitylog.dto.LogDto;
import com.lening.communitylog.pojo.Log;
import com.lening.communitylog.mapper.LogMapper;
import com.lening.communitylog.service.LogService;
import com.lening.communitylog.vo.LogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 操作日志表 服务实现类
 * </p>
 *
 * @author
 * @since 2024-06-04
 */
@Service
public class LogServiceImpl extends BaseServiceImpl<LogMapper, Log, LogDto> implements LogService {

    @Autowired(required = false)
    private LogMapper logMapper;


    @Override
    @Transactional
    @Scheduled(cron = "0 0 0 * * ?")  //每天凌晨创建一次
//     @Scheduled(cron = "10 * * * * ?")   //每十秒创建一次
    public void createTable() {
        logMapper.createTable("t_log_" + LocalDate.now().toString().replace("-", "_"));
    }


    @Override
    public Page<?> page(LogDto logDto) {
        logDto.setTableName(logDto.getTableName().toString().replaceAll("-", "_"));
        return logMapper.page(logDto);
    }

    @Override
    @Transactional
    @Scheduled(cron = "0 0 0 * * ?")
    public void deleteTable() {
        // 计算30天前的日期
        logMapper.deleteTable("t_log_" + LocalDate.now().minusDays(30).toString().replace("-", "_"));

    }

    @Override
    public long getTotalCounts(List<String> tableNames) {
        long totalCount = 0;
        for (String tableName : tableNames) {
            // 注意：这里可能需要处理SQL注入的风险
            long count = logMapper.getTotalCounts(Collections.singletonList(tableName));
            totalCount += count;
        }
        return totalCount;
    }

    @Override
    public void addLog(LogVo logVo) {
        String tableName = "t_log_" + LocalDate.now().toString().replace("-", "_");
        logMapper.addLog(logVo, tableName);
    }

    @Override
    public List<String> getTableNamePage() {
        return logMapper.getTableName();
    }

}
